//
//  JsRequestUtil.m
//  JsUtilitySdk
//
//  Created by Gikki Ares on 2023/4/10.
//

#import "JsRequestUtil.h"
#import "JsYy_Model.h"
@implementation JsRequestUtil



//
+ (void)handleResponseObject:(id)responseObject
					response:(NSHTTPURLResponse *_Nullable)response
					   error:(NSError * _Nullable)error
					  config:(JsRequestConfig *)config
						info:(JsRequestInfo *)info
				  completion:(JsResponseHandler)completion {
	
	
	//处理responseStateCode
	if(response) {
		info.responseHeader = response.allHeaderFields;
		info.responseStateCode = response.statusCode;
		info.responseStateMessage = [self messageForStateCode:info.responseStateCode];
	}
	else {
		if(error){
			info.responseStateCode = JsResponseStateInvalid;
			NSString * errMessage = [error localizedDescription];
			if(errMessage) {
				info.responseStateMessage = errMessage;
			}
			else {
				info.responseStateMessage = error.userInfo.description;
			}
		}
		else {
			info.responseStateCode = JsResponseStateOk;
		}
	}
	info.responseHeader = [response.allHeaderFields copy];
	[self handleResponseObject:responseObject error:error config:config info:info completion:completion];
}


/**
 1,将responseobject转化为和config中的一致.
 */
+ (void)handleResponseObject:(id _Nullable)responseObject
					   error:( NSError  * _Nullable  )error
					  config:(JsRequestConfig *)config
						info:(JsRequestInfo *)info
				  completion:(JsResponseHandler)completion {
	NSString * url = [config requestUrlString];
	NSString * strDetail = nil;
	info.urlString = url;
	info.methodName = [config requestMethodName];
	info.requestEndTime = CFAbsoluteTimeGetCurrent();
	info.requestBodyInputString = [config requestBodyInputString];
	info.requestBodyInputType = config.requestBodyInputType;
	info.responseBodyData = responseObject;
	info.responseBodyOutputType = config.responseBodyOutputType;
	
//		//计算返回数量的大小
//	if([config.isCalculateTraffic boolValue]) {
//		NSData * dataResponse = [responseObject jsyy_modelToJSONData];
//		NSString * strResponseLength = [self sizeDescriptionForBytesSize:dataResponse.length];
//	}

	
//		//1.1 请求头的数据
//			{ //Todo:
//				NSString * str = @"None";
//				NSMutableDictionary * mdic = [NSMutableDictionary dictionary];
//				[mdic addEntriesFromDictionary:info.requestHeader];
//				if(info.cookies.count) {
//					NSMutableString * str = [NSMutableString string];
//					[info.cookies enumerateObjectsUsingBlock:^(NSHTTPCookie *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//						if(idx !=0) {
//							[str appendString:@";"];
//						}
//						[str appendFormat:@"%@=%@",obj.name,obj.value];
//					}];
//					mdic[@"Cookie"]=str;
//				}
//				if(mdic.allKeys.count) {
//					str = [mdic jsyy_modelToJSONString];
//				}
//				[mstrDetail appendFormat:@"RequestHeader:%@\n",str];
//			}
	
	
	
	
	/**
	 1,按照config的outputType,转换NSData.
	 2,有的情况没有响应体,比如超时.
	 */
	NSString * responseOutputString = @"";
	id parsedResponseObject = nil;
	if(responseObject) {
		switch(config.responseBodyOutputType) {
			case JsResponseBodyOutputTypeData:
				parsedResponseObject = responseObject;
					//不用转换,得到的就是nsdata;
			case JsResponseBodyOutputTypeJsonToMap:{
					//得到的data是jsondata,并且需要转换为map
				//afnetworking直接解析的就是dic.
				if([responseObject isKindOfClass:[NSDictionary class]]) {
					responseOutputString = [responseObject jsyy_modelToJSONString];
					parsedResponseObject = responseObject;
				}
				else {
					//urlsession返回的是nsdata
					responseOutputString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
					parsedResponseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
				}
				break;
			}
			case JsResponseBodyOutputTypeJsonToArray:{
					//得到的data是jsondata,并且需要转换为array:
				responseOutputString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
				parsedResponseObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
				break;
			}
			case JsResponseBodyOutputTypeString:{
				if([responseObject isKindOfClass:[NSData class]]) {
					responseOutputString = parsedResponseObject = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
				}
			}
		}
	}
	
	info.responseBodyOutputString = responseOutputString;
	NSString * errMessage = [error localizedDescription];
	if(!errMessage) {
		errMessage = [error userInfo].description;
	}
		//2 通用处理
	completion((int)info.responseStateCode,parsedResponseObject,errMessage ,info);
}

static NSArray * _arrUnit;
+(void)load{
	_arrUnit= @[@"B",@"KB",@"MB",@"GB",@"TB"];
}
+ (NSString *)sizeDescriptionForBytesSize:(uint32_t)size {
	NSString *unit;
	double dsize = size;
	int i = 0;
	for(;i<dsize;i++) {
		if(dsize>1024) {
			dsize/=1024;
		}
		else {
			break;
		}
	}
	unit = _arrUnit[i];
	NSString *strRet =[NSString stringWithFormat:@"%.2f%@",dsize,unit];
	return strRet;
}

#pragma mark 2 InnerFunc
+(NSString *)messageForStateCode:(long)statusCode {
	switch(statusCode) {
		case 200:{
			return @"响应成功";
		}
		case 500:{
			return @"服务器异常";
		}
		default:
			return @"响应失败";
	}
}

@end
